<script>
import numberUtils from "@/utils/numberUtils"
import selectPopup from "@/components/coupon/selectPopup.vue"
import request from "@/utils/request"
import pay from "@/utils/pay"
import bindPhoneNumberPopup from "@/components/bindPhoneNumberPopup/index.vue"
import store from "@/store"
import { userActionType } from "@/store/modules/user"

export default {
  name: "takeOrder",
  components: {
    selectPopup,
    bindPhoneNumberPopup,
  },
  computed: {
    numberUtils() {
      return numberUtils
    },
  },
  props: {
    details: {
      type: Object,
      default: () => ({}),
    },
		needBindPhone: {
			type: Boolean,
			default: true,
		},
		// 下单之前是否需要选择考试
		needSelectExam: {
			type: Boolean,
			default: false,
		}
  },
  data() {
    return {
      couponDiscount: 0, // 优惠券减免金额
      finalPrice: 0, // 最终价格
      noCoupon: false,
      userCouponId: "",
    }
  },
  methods: {
    // 	下单支付购买
    async takeOrder() {
			if (this.needSelectExam) {
				const examInfo = await store.dispatch(userActionType.action.examInfo)
				if (!examInfo) {
					// 跳转到考试选择页面
					uni.navigateTo({
						url: "/pages/examSelection/index",
					})
					return
				}
			}
      // 如果没有绑定手机号码打开绑定手机号码弹框
      this.needBindPhone && await this.$refs.bindPhoneNumberPopup.open()
      // 打开选择优惠券弹窗（如果有的话）
      await this.$refs.selectPopup.openPopup()
      // 创建订单
      const data = await request({
        url: "studyActivity/createOrder",
        data: {
          studyActivityId: this.details.studyActivityId,
          userCouponId: this.userCouponId,
        },
        errorHandle: true,
        showLoading: true,
      })
      // 拉取支付
      await pay.handlePay(data)
      // 支付完成回调
      this.$emit("afterPay")
    },
  },
  emits: ["afterPay"],
}
</script>

<template>
  <view class="component">
    <view class="join-activity-btn d-flex align-center justify-center" @click="takeOrder">
      <text>{{ `${numberUtils.fenToYuan(finalPrice)}元加入` }}</text>
    </view>

    <selectPopup
      ref="selectPopup"
      :couponTypeList="[0, 4]"
      :origin-price="details.price"
      :coupon-discount.sync="couponDiscount"
      :no-coupon.sync="noCoupon"
      :userCouponId.sync="userCouponId"
      :final-price.sync="finalPrice"
      :allowExchange="false"
    ></selectPopup>

    <bindPhoneNumberPopup ref="bindPhoneNumberPopup">
      <view>
        <text>为了更好的监督学生完成期末备考营学习打卡任务，方便学长跟进大学的学习情况，</text>
        <text style="color: #df541c; text-decoration: underline"
          >参与报名时请留下你的手机号码，学长会及时联系拉你进群，开展后续的学习任务。</text
        >
      </view>
    </bindPhoneNumberPopup>
  </view>
</template>

<style scoped lang="scss">
.join-activity-btn {
  position: fixed;
  bottom: calc(10vh + env(safe-area-inset-bottom));
  left: 50%;
  transform: translateX(-50%);
  width: 380rpx;
  height: 100rpx;
  color: white;
  font-size: 32rpx;
  background: #ff6219;
  border-radius: 50rpx;
}
</style>
